package pers.mihao.ancient_empire.auth.annotation.handle;

import pers.mihao.ancient_empire.auth.annotation.SystemUserName;

import javax.validation.ConstraintValidator;
import javax.validation.ConstraintValidatorContext;
import java.util.regex.Matcher;
import java.util.regex.Pattern;

public class SystemUserNameValidator implements ConstraintValidator<SystemUserName, Object> {

	public static final String ERROR_INFO = "用户名必须由4-8英文或中文组成";

	@Override
	public void initialize(SystemUserName constraintAnnotation) {

	}

	@Override
	public boolean isValid(Object o, ConstraintValidatorContext constraintValidatorContext) {
		if (o == null) {
			return false;
		}
		String value = o.toString();
		if (value.length() < 4 || value.length() > 8) {
			return false;
		}
		return isMatcher(value);
	}

	/**
	 * 是否是汉字
	 *
	 * @param string
	 * @return
	 */
	public boolean isMatcher(String string) {
		Pattern p = Pattern.compile("^[a-zA-Z\u4e00-\u9fa5]+$");
		Matcher m = p.matcher(string);
		if (m.matches()) {
			return true;
		}
		return false;
	}
}
